#!/usr/python3
# coding=utf-8

import json
import os
import pandas as pd
import time


def extract_api_from_file(json_file):
    case_info = []
    if json_file:
        with open(json_file, "r", encoding="utf8") as f:
            json_content = json.load(f)[0]

        # print(type(json_content))
        # print(json_content)
        # 读取 云测脚本中的Case 内容

        testcases = json_content["case"] if "case" in json_content.keys() else None
        if testcases:
            for case in testcases:
                case_name = case["name"]
                case_steps = case["steps"]
                for step in case_steps:
                    if step["type"] in ["http", "http-multipart"]:
                        url = step["input"]["url"]
                        url_flag = "/v1" + url.split("/v1")[-1]
                        method = step["input"]["method"]
                        # print(f'{json_file}; {case_name}; {method}; {url}')
                        print(
                            "{}; {}; {}; {}".format(json_file, case_name, method, url)
                        )
                        case_info.append([json_file, case_name, method, url, url_flag])

    return case_info


def save_case_api_2_excel(root_path, target_file):
    # 获取指定的文件夹路径，并读取所有的JSON格式文件
    # print(os.listdir(root_path))
    total_api_cases = []
    per_api_cases = []
    for dirpath, _, filenames in os.walk(root_path):
        final_paths = [os.path.join(dirpath, names) for names in filenames]
        for path in final_paths:
            print(path)
            _, file_extension = os.path.splitext(path)
            if file_extension == ".json":
                # print(path)
                total_api_cases.extend(extract_api_from_file(path))
                # break

    # 列表数据转为数据框并生成Excel文件
    df = pd.DataFrame(
        total_api_cases,
        columns=["File_Name", "Case_Name", "API_Method", "API_Path", "API_Flag"],
    )
    df.to_excel(target_file, sheet_name="Designed_API_List", index=False)


def extract_content_from_response(response):
    # 基于API的结构，完成最基础的接口响应的解析
    code, content = False, None
    http_status_code = response.status_code
    if http_status_code == 200:
        http_content = json.loads(response.text)
        if isinstance(http_content, dict):
            resp_code = http_content["code"]
            if resp_code in ["BLACZZ0200", "BLACZZ0202"]:
                code = True
                content = (
                    http_content["result"] if "result" in http_content.keys() else None
                )
                return code, content

    http_content = json.loads(response.text)
    error = http_content.get("message")
    message = error
    content = message if message else error
    return code, content
    


if __name__ == "__main__":
    # json_file = 'D:/MyProjects/bill_center_test/bill_engine_api/data_controller/data_service.json'
    # extract_api_from_file(json_file)
    timestamp = time.strftime("%Y%m%d", time.localtime())
    # root_path = 'D:/MyProjects/Billings/bill_center_test/bill_iteration'
    # target_file = f'D:/MyProjects/Billings/BillCenter_TestData/{timestamp}_bill_testcases.xlsx'
    # save_case_api_2_excel(root_path, target_file)
    # root_path = 'D:/MyProjects/Billings/bill_center_test/bill_engine_iteration'
    # target_file = f'D:/MyProjects/Billings/BillCenter_TestData/{timestamp}_bill_engine_testcases.xlsx'
    # target_file = 'D:/MyProjects/Billings/BillCenter_TestData/demo.xlsx'
    # save_case_api_2_excel(root_path, target_file)
